/**
 * Notes: 样片模块业务逻辑
 */

const BaseProjectService = require('./base_project_service.js');
const dataUtil = require('../../../framework/utils/data_util.js');
const util = require('../../../framework/utils/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const CommentModel = require('../model/comment_model.js');
const UserModel = require('../model/user_model.js');

class CommentService extends BaseProjectService {

	/** 点赞 */
	async likeComment(userId, id) {
    try {
      // 获取留言详情
      let comment = await this.getLeaveDetail(id);
      if (!comment) {
          return {
              code: -1,
              message: '点赞信息不存在',
              data: null
          };
      }
      
      // 获取当前点赞列表
      let arr = comment['COMMENT_LIKE_LIST'];

      // 定义一个标志位，用于表示是否已经点赞
      let flag = false;

      // 检查用户是否已经在点赞列表中
      if (arr.includes(userId)) {
          // 如果用户已经点赞了，则取消点赞
          arr = arr.filter(item => item != userId);
          flag = false; // 表示取消点赞
      } else {
          // 如果用户未点赞，则执行点赞操作
          arr.push(userId);
          flag = true; // 表示点赞
      }
      
      // 更新留言详情中的点赞列表和点赞数量
      await CommentModel.edit(id, {
          ["COMMENT_LIKE_LIST"]: arr,
          ["COMMENT_LIKE_CNT"]: arr.length
      });

      return {
        isLike:flag
      };
  } catch (err) {
      console.error('[点赞操作失败]', err);
      return {
          code: -1,
          message: '点赞操作失败：' + err.message,
          data: null
      };
  }
	}

	async statComment(oid, type) {
		let PREFIX = type.toUpperCase();
		let name = type.toLowerCase();

		let cnt = await CommentModel.count({ COMMENT_OID: oid, COMMENT_TYPE: type });
		let Model = require('../model/' + name + '_model.js');

		await Model.edit(oid, { [PREFIX + '_COMMENT_CNT']: cnt });
	}

	async delComment(userId, id, type) {
	  try {
      await CommentModel.del(userId,id,type);
      return {
          code: 0,
          message: '删除留言成功',
          data: null
      };
  } catch (err) {
      console.error('[删除留言失败]', err);
      return {
          code: -1,
          message: '删除留言失败' + err.message,
          data: null
      };
  }
	}

	async insertComment(userId, {
		oid,
		type,
		forms
	}) {

    try {
      let data = {
        COMMENT_USER_ID : userId,
        COMMENT_OID : oid,
        COMMENT_TYPE : type,
        COMMENT_OBJ : dataUtil.dbForms2Obj(forms),
        COMMENT_FORMS : forms
      }

      await CommentModel.insert(data)
         // 返回插入成功的结果
         return {
          code: 0,
          message: '插入留言成功',
          data: result
      };
    }catch (err) {
      // 如果发生错误，可以捕获错误并进行处理
      console.error('[插入留言失败]', err);
      // 返回错误信息
      return {
          code: -1,
          message: '插入留言失败：' + err.message,
          data: null
      };
    }}

	// 更新forms信息
	async updateCommentForms({
		id,
		hasImageForms
	}) {
    try {
      const cloud = cloudBase.getCloud();
      const fileIDs = await Promise.all(hasImageForms.map(async image => {
          const res = await cloud.uploadFile({
              cloudPath: 'comment_images/' + dataUtil.getUniqueFileName(image.name),
              fileContent: image.data,
          });
          return res.fileID;
      }));

      const result = await LostModel.edit(id, { COMMENT_IMAGES: fileIDs });
      return {
          code: 0,
          message: '更新图片成功',
          data: result
      };
  } catch (err) {
      console.error('[更新图片失败]', err);
      return {
          code: -1,
          message: '更新图片失败：' + err.message,
          data: null
      };
  }

	}

	async getCommentList(userId, {
		oid,
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal }) {
		orderBy = orderBy || {
			'COMMENT_ADD_TIME': 'desc'
		};
		let fields = 'COMMENT_LIKE_CNT,COMMENT_LIKE_LIST,COMMENT_ADD_TIME,COMMENT_USER_ID,COMMENT_OBJ,user.USER_NAME,user.USER_PIC,user.USER_OBJ.sex';


		let where = {};
		where.and = {
			COMMENT_OID: oid,
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};


		if (util.isDefined(search) && search) {
			where.or = [
				{ 'COMMENT_OBJ.content': ['like', search] },
				{ 'user.USER_NAME': ['like', search] },
			];


		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'COMMENT_ADD_TIME');
					break;
				}
				case 'like': {
					orderBy = {
						'COMMENT_LIKE_CNT': 'desc',
						'COMMENT_ADD_TIME': 'desc'
					}
					break;
				}
				case 'mycomment': {
					where.and.COMMENT_USER_ID = userId;
					break;
				}
				case 'mylike': {
					where.and.COMMENT_LIKE_LIST = userId;
					break;
				}

			}
		}

		let joinParams = {
			from: UserModel.CL,
			localField: 'COMMENT_USER_ID',
			foreignField: 'USER_MINI_OPENID',
			as: 'user',
		};

		return await CommentModel.getListJoin(joinParams, where, fields, orderBy, page, size, isTotal, oldTotal);
	}

}

module.exports = CommentService;